package com.example.xuegengwang.xuegengwang.fragment;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.listener.OnItemClickListener;
import com.example.xuegengwang.xuegengwang.MainActivity;
import com.example.xuegengwang.xuegengwang.R;
import com.example.xuegengwang.xuegengwang.adapter.MainPageListViewAdapter;
import com.example.xuegengwang.xuegengwang.adapter.MainPageMenuAdapter;
import com.example.xuegengwang.xuegengwang.bean.MainIndexBean;
import com.google.gson.Gson;


import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import common.Constant;
import https.InterNetController;
import https.handler.ErrorPageHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import utils.CalculateUtils;
import view.MyGridView;
import view.MyPtrRefresh_LoadView;
import view.NetworkImageHolderView;

import java.util.ArrayList;
import java.util.List;

import common.BaseFragment;
import utils.MyLogUtils;

@SuppressLint("ValidFragment")
public class MainPageFragment extends BaseFragment implements OnItemClickListener, View.OnClickListener {
    private ListView listView;
    private View listViewHeader;
    private MyGridView main_page_menu;
    private MainPageMenuAdapter mainPageMenuAdapter;
    private MainPageListViewAdapter mainPageListViewAdapter;//显示listView用的adapter
    private ConvenientBanner main_page_viewpager;//轮播图
    private ArrayList<MainIndexBean.ExpertBean> arrayList;//志愿者数组
    private LayoutInflater layoutInflater;
    private View view;//主页
    //    private RelativeLayout main_page_search_layout;//搜索框
    private List<String> networkImages;
    private List<MainIndexBean.BannerBean> bannerList;//轮播图的数组;
    private List<MainIndexBean.MenuBean> menuList;//中间菜单的数组;
    private ArrayList<MainIndexBean.ExpertBean> expertList;//志愿者的数组
    private LinearLayout main_listView_header_more;//更多
    private MyPtrRefresh_LoadView main_page_refreshLayout;//可以下拉刷新

    private static final String TAG = "MainPageFragment";
    private final int GET_INDEX = 0;
    private final int GETMENU = 1;
    private int count;
    private boolean isFirstOpen;//判断是否第一次打开本页

    private ErrorPageHandler myHandler = new ErrorPageHandler(true) {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {
                case Constant.ERROR_CODE_SUCCESS://返回正确的信息
                    switch (msg.arg1) {
                        case GET_INDEX:
                            if (main_page_refreshLayout != null) {
                                main_page_refreshLayout.OnRefreshComplete();
                            }
                            Gson gson = new Gson();
                            String data_s = (String) msg.obj;
                            MainIndexBean mainIndexBean = gson.fromJson(data_s, MainIndexBean.class);
                            if (mainIndexBean != null) {
                                if (mainIndexBean.getBanner() != null && mainIndexBean.getBanner().size() > 0) {
                                    bannerList = mainIndexBean.getBanner();//获得轮播图
                                    setBanner(bannerList);//设置轮播动画
                                }
                                if (mainIndexBean.getMenu() != null && mainIndexBean.getMenu().size() > 0) {
                                    List<MainIndexBean.MenuBean> menu = mainIndexBean.getMenu();
                                    menuList.clear();
                                    for (int i = 0; i < menu.size(); i++) {
                                        menuList.add(menu.get(i));//获得菜单图
                                    }
                                    CalculateUtils.setListViewHeightBasedOnChildren(main_page_menu);
                                    mainPageMenuAdapter.notifyDataSetChanged();
                                }
                                expertList = (ArrayList<MainIndexBean.ExpertBean>) mainIndexBean.getExpert();//获得志愿者
                                if (expertList != null) {
                                    arrayList.clear();
                                    for (int i = 0; i < expertList.size(); i++) {
                                        arrayList.add(expertList.get(i));
                                    }
                                }
                                mainPageListViewAdapter.notifyDataSetChanged();
                                isFirstOpen = false;
                            }
                            break;
                        case GETMENU:
                            try {
                                JSONObject jsonObject = new JSONObject(String.valueOf(msg.obj));
                                JSONArray menu = jsonObject.getJSONArray("menu");
                                if (menu != null) {
                                    menuList.clear();
                                    Gson gson1 = new Gson();
                                    for (int i = 0; i < menu.length(); i++) {
                                        MainIndexBean.MenuBean menuBean = gson1.fromJson(menu.get(i).toString(), MainIndexBean.MenuBean.class);
                                        menuList.add(menuBean);//获得菜单图
                                    }
                                    CalculateUtils.setListViewHeightBasedOnChildren(main_page_menu);
                                    mainPageMenuAdapter.notifyDataSetChanged();
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            break;
                        case Constant.ERROR_CODE_FAILD:
                            if (main_page_refreshLayout != null) {
                                main_page_refreshLayout.OnRefreshComplete();
                            }
                            break;
                        default:
                            break;
                    }
                    break;
                case 1000:
                    MyLogUtils.e(TAG, "hahahahahaha");
                    break;
                case Constant.ERROR_CODE_FAILD:
                    if (main_page_refreshLayout != null) {
                        main_page_refreshLayout.OnRefreshComplete();
                    }
                    break;
                default:
                    break;

            }
        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.main_page_fragment1, container, false);
        if (getMyActivity() != null) {
            initView();
            initData();
            initListView();
            isFirstOpen = true;
        }
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        if (isFirstOpen) {
            GetDataFromInterNet(true);
        } else {
            getMenu();
        }
    }

    private void initView() {
        menuList = new ArrayList<>();
        listView = (ListView) view.findViewById(R.id.main_page_listView);
        layoutInflater = getMyActivity().getLayoutInflater();
        listViewHeader = layoutInflater.inflate(R.layout.main_listview_header, null);//添加头部
        main_page_menu = (MyGridView) listViewHeader.findViewById(R.id.main_page_menu);
        mainPageMenuAdapter = new MainPageMenuAdapter(getMyActivity(), menuList);
        main_page_menu.setAdapter(mainPageMenuAdapter);
        main_page_viewpager = (ConvenientBanner) listViewHeader.findViewById(R.id.main_page_banner);
//        main_page_search_layout = (RelativeLayout) view.findViewById(R.id.main_page_search_layout);
        main_listView_header_more = (LinearLayout) listViewHeader.findViewById(R.id.main_listView_header_more);//更多
        main_page_refreshLayout = (MyPtrRefresh_LoadView) view.findViewById(R.id.main_page_refreshLayout);
        main_page_refreshLayout.ChangeMode(true, false);
        main_page_refreshLayout.setMyPtrHandler(new MyPtrRefresh_LoadView.MyPtrHandler() {
            @Override
            public void onLoadMoreBegin(PtrFrameLayout frame) {

            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                GetDataFromInterNet(false);
            }
        });
//        main_page_search_layout.setOnClickListener(this);
        main_listView_header_more.setOnClickListener(this);
        //TODO
        //记得删掉
//        main_page_search_layout.setVisibility(View.GONE);
    }

    private void initData() {
        arrayList = new ArrayList<>();
    }

    private void initListView() {
        listView.addHeaderView(listViewHeader);
        mainPageListViewAdapter = new MainPageListViewAdapter(getActivity(), arrayList);
        listView.setAdapter(mainPageListViewAdapter);
    }

    private void GetDataFromInterNet(boolean waitingDialog) {
        new InterNetController(getMyActivity(), Constant.MAIN_INDEX, myHandler, null, GET_INDEX, waitingDialog);
    }

    private void getMenu() {
        new InterNetController(getMyActivity(), Constant.GETMENU, myHandler, null, GETMENU, false);
    }

    private void setBanner(List<MainIndexBean.BannerBean> banner) {
        //设置轮播图片
        networkImages = new ArrayList<>();
        if (banner != null) {
            for (int i = 0; i < banner.size(); i++) {
                networkImages.add(banner.get(i).getImage());
            }
        }
        main_page_viewpager.setPages(new CBViewHolderCreator<NetworkImageHolderView>() {
            @Override
            public NetworkImageHolderView createHolder() {
                return new NetworkImageHolderView();
            }
        }, networkImages)
                .setPointViewVisible(true)//设置指示器是否可见
                .startTurning(2000)
                .setPageIndicator(new int[]{R.mipmap.main_doc1, R.mipmap.main_doc}) //设置指示器圆点;
                .setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.ALIGN_PARENT_RIGHT)
                .setOnItemClickListener(this);
    }

    @Override
    public void onItemClick(int position) {
        //点击轮播图片的事件
        if (bannerList != null) {
            getMyActivity().drumpActivity(bannerList.get(position).getLink());
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        layoutInflater = null;
        expertList = null;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
//            case R.id.main_page_search_layout:
//                Intent i = new Intent(getMyActivity(), ExpertEvaluate.class);
//                startActivity(i);
//                break;
            case R.id.main_listView_header_more:
                ((MainActivity) getMyActivity()).goToOnlineAsk();
                break;
            default:
                break;
        }
    }
}
